package com.example.extenddemo.handle;

import cn.hutool.core.bean.BeanUtil;
import com.example.extenddemo.config.GAEnum;
import com.example.extenddemo.config.MyJson;
import com.example.extenddemo.utils.SpringUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.awt.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
public class MyJsonHandler extends JsonSerializer<String> implements ContextualSerializer {

    // 考虑线程安全问题
    private final ThreadLocal<String> keyCache = new ThreadLocal<>();

    @Resource
    private List<GAEnum> enumList;

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        log.info("使用扩展.....................");
        String key = keyCache.get();
        if(Objects.nonNull(key)){
            jsonGenerator.writeString(String.format("%s:%s", key, s));
            keyCache.remove();
        }else{
            jsonGenerator.writeString(s + "追加的信息");
        }
    }

    @SneakyThrows
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        MyJson annotation = beanProperty.getAnnotation(MyJson.class);
        Class<Object> objectClass = annotation.type();
        if(Objects.nonNull(objectClass)){
            Object[] enumConstants = objectClass.getEnumConstants();
            Field field = objectClass.getField(annotation.Key());
            Object o = field.get(objectClass);
        }
        beanProperty.getName();
        if(Objects.nonNull(annotation) && Objects.equals(String.class, beanProperty.getType().getRawClass())){
            log.info("MyJsonHandler start ..............");
            if(Objects.nonNull(annotation.Key())){
                keyCache.set(annotation.Key());
            }
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(),beanProperty);
    }
}
